package mvc.core;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;



import mvc.model.ActionBean;

public class XmlParseUtil {
	private static Map<String, String> formMap = new HashMap<String,String>();
	private static Map<String,ActionBean> actionMap = new HashMap<String,ActionBean>();
	
	public static Map<String, ActionBean> parseXml(File file){
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(file);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		parseForm(document);
		parseActionBean(document);
		System.out.println(actionMap);
		return actionMap;
	}

	private static void parseActionBean(Document document) {
		Element rootElement = document.getRootElement();
		Element actionElement = rootElement.element("actions");
		List<Element> elements = actionElement.elements();
		Map<String, String> map = new HashMap<String,String>();
		for(Element e : elements){
			String name = e.attributeValue("name");
			String actionType = e.attributeValue("type");
			String path = e.attributeValue("path");
			ActionBean actionBean = new ActionBean();
			actionBean.setActionType(actionType);
			actionBean.setName(name);
			actionBean.setPath(path);
			String formType = formMap.get(name);
			if(formType != null){
				actionBean.setFormType(formType);
			}
			List<Element> resultElements = e.elements("result");
			for(Element f : resultElements){
				String resultName = f.attributeValue("name");
				String resultValue = f.attributeValue("value");
				map.put(resultName, resultValue);
			}
			actionBean.setResultMap(map);
			actionMap.put(path, actionBean);
		}
		
	}

	private static void parseForm(Document document) {
		Element rootElement = document.getRootElement();
		Element formElement = rootElement.element("formbeans");
		List<Element> elements = formElement.elements();
		for(Element e : elements){
			String name = e.attributeValue("name");
			String clazz = e.attributeValue("class");
			formMap.put(name, clazz);
		}
		
	}
	
	public static void main(String[] args) {
		File file = new File("WebRoot/WEB-INF/mvc-config.xml");
		parseXml(file);
	}
}
